import 'package:flutter/material.dart';
import 'package:flutter_shop/model/cartinfo.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';


class CartProvide with ChangeNotifier{
  String cartString="[]";
  List<CartInfoModel> cartList=[];

  save(goodsId,goodsName,count,price,images) async{
    SharedPreferences prefs=await SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo');
    var temp=cartString==null?[]:json.decode(cartString.toString());
    List<Map> tempList=(temp as List).cast();
    bool isHave=false;
    int ival=0;
    tempList.forEach((item){
      if(item['goodsId']==goodsId){
        tempList[ival]['count']=item['count']+1;
        if(cartList[ival]!=null){//第一次的时候要判断cartlist[ival]是否存在
          cartList[ival].count++;
        }        
        isHave=true;        
      }
      ival++;
    });
    if(!isHave){
      Map<String,dynamic> newGoods={
        'goodsId':goodsId,
        'goodsName':goodsName,
        'count':count,
        'price':price,
        'images':images,
        'isCheck':true
      };
      tempList.add(newGoods);
      cartList.add(CartInfoModel.fromJson(newGoods));
    }
    cartString=json.encode(tempList).toString();
    prefs.setString('cartInfo', cartString);
    print('字符串================================》${cartString}');
     print('数据模型================================》${cartList}=====>${cartList[0].count}');
    notifyListeners();
  }

  remove() async{
    SharedPreferences prefs=await SharedPreferences.getInstance();
    prefs.remove('cartInfo');
    cartList=[];
    print('清空完成....................................................................');
    notifyListeners();
  }
  
  getCartInfo() async{
    SharedPreferences prefs=await SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo');
    cartList=[];
    if(cartString==null){
      cartList=[];
    }else{
      List<Map> tempList=(json.decode(cartString.toString()) as List).cast();
      tempList.forEach((item){
        cartList.add(CartInfoModel.fromJson(item));
      });
    }
    notifyListeners();
  }

  //删除单个购物车商品
  deleteOneGoods(String goodsid) async {
    SharedPreferences prefs=await SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo');
    //将string 转换为list
    List<Map> tempList=(json.decode(cartString.toString()) as List).cast();
    int tempIndex=0;
    int deleteIndex=0;
    tempList.forEach((item){
      if(item['goodsId']==goodsid){
        deleteIndex=tempIndex;
      }
        tempIndex++;
    });
    //去除后，持久化
    tempList.removeAt(deleteIndex);
    cartString=json.encode(tempList).toString();
    prefs.setString('cartInfo',cartString);
    await getCartInfo();
  }
}